# -*- coding: utf-8 -*-
"""
@Time ：2021/3/25 21:11 
@Auth ： Mr. William 1052949192
@Company ：特斯汀学院 @testingedu.com.cn
@Function ：滑块验证码
"""
import time
from requests import get
import cv2
from selenium.webdriver import Chrome, ActionChains

from common.Logger import path


class Slide:
    """滑块验证码识别"""

    def __init__(self, driver):
        self.driver: Chrome = driver

    def FindPic(self, bg="../lib/verify/bg.png", block="../lib/verify/block.png"):
        """
        找出图像中最佳匹配位置
        :param bg: 目标即背景图
        :param block: 模板即需要找到的图
        :return: 返回最佳匹配及其最差匹配和对应的坐标
        """
        # 读取图片
        target_rgb = cv2.imread(bg)
        # 进行灰度处理
        target_gray = cv2.cvtColor(target_rgb, cv2.COLOR_BGR2GRAY)
        # 读取图片
        template_rgb = cv2.imread(block, 0)
        # 匹配缺口在背景图的位置
        res = cv2.matchTemplate(target_gray, template_rgb, cv2.TM_CCOEFF_NORMED)
        # 获取最差和最佳匹配
        value = cv2.minMaxLoc(res)
        print(value)
        # 返回最佳匹配的x坐标
        return value[2][0]

    def slide_img(self, xpath_bg: str = '', xpath_block: str = '', xpath_refresh: str = ''):
        """
        滑块验证码实现
        :param xpath_bg: 背景定位
        :param xpath_block: 模块定位
        :return:
        """

        while True:
            # 获取下载链接
            ele_bg = self.driver.find_element_by_xpath(xpath_bg)
            src_bg = ele_bg.get_attribute('src')

            ele_block = self.driver.find_element_by_xpath(xpath_block)
            src_block = ele_block.get_attribute('src')

            # 下载图片
            bg_con = get(src_bg).content
            f = open(path + '/lib/verify/bg.jpg', mode='wb')
            # 写入图片的二进制码
            f.write(bg_con)
            f.close()
            block_con = get(src_block).content
            f = open(path + '/lib/verify/block.jpg', mode='wb')
            f.write(block_con)
            f.close()

            x = self.FindPic(path + '/lib/verify/bg.jpg', path + '/lib/verify/block.jpg')
            x = int(x * ele_bg.size.get('width') / 680) -22
            print(x)

            action = ActionChains(self.driver)
            # 按住
            action.click_and_hold(ele_block).perform()
            # 拖动
            action.move_by_offset(x, 0).perform()
            # 放开鼠标
            action.release().perform()
            time.sleep(2)
            # 通过判断是否有刷新按钮，来确定是否重试
            try:
                self.driver.find_element_by_xpath(xpath_refresh).click()
            except:
                break
